package com.wj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.dao.EmployeeMapper;
import com.wj.dto.RespPageDTO;
import com.wj.pojo.Employee;
import com.wj.pojo.MailConstants;
import com.wj.pojo.MailLog;
import com.wj.pojo.RespBean;
import com.wj.service.IEmployeeService;
import com.wj.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wj
 * @since 2022-03-06
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    IMailLogService mailLogService;

    /**
     * 获取所有员工（分页）
     *
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public RespPageDTO getAllEmployee(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> allEmployee = employeeMapper.getAllEmployee(page, employee, beginDateScope);
        RespPageDTO respPageDTO = new RespPageDTO(allEmployee.getTotal(), allEmployee.getRecords());
        return respPageDTO;
    }

    /**
     * 获取工号
     *
     * @return
     */
    @Override
    public RespBean maxWorkID() {
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        String format = String.format("%08d", Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1);
        return RespBean.success(null, format);
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @Override
    public RespBean addEmployee(Employee employee) {
        //计算工龄
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.YEARS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.00)));

        if (employeeMapper.insert(employee) > 0) {
            //数据库记录发送的消息
            String msgID = UUID.randomUUID().toString();
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgID);
            mailLog.setEid(employee.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogService.save(mailLog);

            //通知消息队列发欢迎邮件
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME
                    , employee, new CorrelationData(msgID));
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    /**
     * 查询员工(可单查一个 复用)
     *
     * @return
     */
    @Override
    public List<Employee> getAllEmployeeById(Integer id) {
        return employeeMapper.getAllEmployeeById(id);
    }

    /**
     * 获取所有员工工资账套
     *
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public RespPageDTO getEmployeeWithSalary(Integer currentPage, Integer size) {
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> iPage = employeeMapper.getEmployeeWithSalary(page);
        return new RespPageDTO(iPage.getTotal(), iPage.getRecords());
    }

}
